package auth

import (
	"fmt"
	"strings"

	"gitee.com/zatto/mcenter/apps/endpoint"
	"gitee.com/zatto/mcenter/apps/token"
	"gitee.com/zatto/mcenter/common/logger"
	"github.com/emicklei/go-restful/v3"
	"github.com/infraboard/mcube/app"
	"github.com/infraboard/mcube/exception"
	"github.com/infraboard/mcube/http/response"
)

type httpAuthor struct {
	token token.Service
}

func NewHttpAuthor() *httpAuthor {
	return &httpAuthor{
		token: app.GetInternalApp(token.AppName).(token.Service),
	}
}

func (a *httpAuthor) AuthFunc(
	req *restful.Request,
	resp *restful.Response,
	next *restful.FilterChain) {
	// 权限判断
	accessRoute := req.SelectedRoute()
	ep := &endpoint.Endpoint{
		Spec: &endpoint.CreateEndpointRequest{
			ServiceId: "",
			Method:    accessRoute.Method(),
			Path:      accessRoute.Path(),
			Operation: accessRoute.Operation(),
		},
	}

	isAuth := accessRoute.Metadata()["auth"]
	if isAuth != nil {
		ep.Spec.Auth = isAuth.(bool)
	}

	fmt.Println(ep)

	// 认证逻辑
	if ep.Spec.Auth {
		// 从header中获取令牌
		authHeader := req.HeaderParameter(token.TOKEN_HEADER_KRY)
		tkl := strings.Split(authHeader, " ")
		if len(tkl) != 2 {
			response.Failed(resp, exception.NewUnauthorized("令牌不合法, 格式： Authorization: breaer xxxx"))
			return
		}
		tk := tkl[1]
		logger.L().Debug().Msgf("get token: %s", tk)

		// token校验
		tkObj, err := a.token.ValidateToken(req.Request.Context(), token.NewValidateTokenRequest(tk))
		if err != nil {
			response.Failed(resp, exception.NewUnauthorized("令牌校验不合法, %s", err))
		}

		// 放入上下文
		req.SetAttribute(token.ATTRIBUTE_TOKEN_KEY, tkObj)
	}

	// 继续下个中间件
	next.ProcessFilter(req, resp)
}
